<template>
  <div class="zombieVehiclesWrap">
    <div class="pageTableInner">
      <div class="infoSearchWrap">
        <div class="infoSearchOne">
          <el-row :gutter="0">
            <el-col :span="6">
              <div class="searchWrap">
                <span class="searchFont">行政区域:</span>
                <span class="searchInputFont">
                  <el-select style="width: 100%;" v-model="searchInfo.parentId"
                             :disabled="$store.state.userInfo.regionId?true:false"
                             @change="changeDistrict(searchInfo.parentId)" size="mini"
                             clearable placeholder="行政区">
                    <el-option
                      v-for="item in $store.state.districtData"
                      :key="item.id"
                      :label="item.regionName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="searchWrap">
                <span class="searchFont">企业:</span>
                <span class="searchInputFont">
                <el-select v-model="searchInfo.enterpriseNo" style="width: 100%;" @change="changeDistribution" size="mini" clearable placeholder="全部">
                      <el-option
                        v-for="item in this.$store.state.companyInfos"
                        :key="item.enterpriseNo+''"
                        :label="item.enterpriseName"
                        :value="item.enterpriseNo+''">
                      </el-option>
                    </el-select>
                </span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="containerWrap" ref="mapScreenfull">
        <div class="infoButton">
          <i @click='screenfullMap' :class="iconFull"></i>
        </div>
        <div class="colorWrap">
          <div v-for="(item,index) in allCompanies" :key="index">
            <span class="colorlist" :style="'background-color:'+item.color"></span>{{item.enterpriseName}} <span style="float: right;color:#3975FE;margin-left: 5px; ">{{item.count}}</span><br/>
          </div>
        </div>
        <div v-show="showloading" class="loadingWrap">
          <div class="loadingInner">
            <img src="./loading.gif">
            <div class="loadingText">单车数据加载中...</div>
          </div>
        </div>
        <div id="container"></div>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    props: [],
    data () {
      return {
        iconFull: "iconfont icon-quanping2",
        searchInfo: {
          "parentId": this.$store.state.userInfo.regionId,
          "regionId": "",
          "enterpriseNo": "",
        },
        showloading:true,
        allCompanies: this.$store.state.companyInfos,
        parentId: "",
        enterpriseId: "",
        mapData: [],
        streetData: [],
        dataM: [{geometry: {type: 'Point', coordinates: [113.95662, 22.530658]}, count: 1}],
        dataIndex: 0,
        map: {},
        fileStrList: [],
        splitMapList: {other: '#fddf01', 1: "#f25b4a", 2: "#fddf01", 3: "#01CBE3"},
        downloadIng: false,
      }
    },
    created(){
      this.axios.post(process.env.API_HOST + '/statis/zombieVehicleDistribution', {})
        .then(response => {
          const result = response.data
          if (result.code == 200) {
            this.fileStrList = result.result.fileStr
          }
        })
    },
    mounted(){
      document.querySelector(".containerWrap").style.height = document.querySelector(".zombieVehiclesWrap").clientHeight - 78 + "px"
      this.getHotMap()

        /*document.onclick = function(){
          alert("这是第一种点击方式");
        }*/
        window.exportZombieVehicle = (ele, id) => {
          ele.classList.add('is-loading')
          this.exportZombieVehicle(ele, id)
        }
    },
    methods: {
      exportZombieVehicle(ele, regionId){
        var data = {regionId:regionId}, str = ''
        data.sign = this.makeSign(data)

        for(let key in data){
          str += key+'='+data[key]
          str += '&'
        }

        window.location.href = process.env.API_HOST + `/statis/exportZombieVehicle?` + str;
        /*if(this.downloadIng){
          return false//下载中
        }
        this.downloadIng = true
        this.axios.post(process.env.API_HOST + `/statis/exportZombieVehicle`, {regionId: regionId}, {responseType: 'arraybuffer'}).then(response => {
          let a = document.createElement('a')
          let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'})
          a.setAttribute('href', URL.createObjectURL(blob))
          a.setAttribute('download', '数据导出.xls')
          a.click()
          
          this.downloadIng = false
          ele.classList.remove('is-loading')
        }).catch(() => {
          this.downloadIng = false
          ele.classList.remove('is-loading')
        })*/
      },
      changeDistribution(){
        this.map.clearOverlays()

        if (!this.parentId) {
          this.$store.state.districtData.forEach(item => {
            this.showArea(JSON.parse(item.regionPoints))
          })
        }else{
          this.$store.state.districtData.forEach(item => {
            if(item.id==this.parentId){
              this.showAreaCenter(JSON.parse(item.regionPoints))
            }
          })
          this.streetData.forEach(item => {
            this.showArea(JSON.parse(item.regionPoints))
          })
        }

        if(this.searchInfo.enterpriseNo||this.parentId){
          this.showloading = true
          this.getMapPage(1)
        }else {
          this.changeDistrict(this.searchInfo.parentId)
        }
      },
      getMapPage(page){
        this.axios.post(process.env.API_HOST + '/statis/zombieDistributionMap', {
          "enterpriseNo":this.searchInfo.enterpriseNo,
          "district":this.parentId,
          "rows":5000,
          "page":page})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              this.mapData=result.result.pointList
              if(result.result.enterpriseNo!=this.searchInfo.enterpriseNo){
                return
              }
              if (this.mapData.length>0) {
                this.mapvSetTwo(page)
              }else {
                this.showloading = false
              }
            }
          })
      },
      mapvSetTwo(index){
        if (this.mapData.length == 0) {
          return
        }
        var dataSet = new mapv.DataSet(this.mapData);
        var options = {
          splitList: this.$store.state.splitMapColors,
          size: 0.6,
          draw: 'category'
        }
        new mapv.baiduMapLayer(this.map, dataSet, options);
        console.log("load" + index + ">>>" + this.dtime().format("HH:mm:ss"))
        //  继续获取
        index++
        this.getMapPage(index)
      },
      getTotalInfo(parentId){
        let id=parentId?parentId:0
        this.axios.post(process.env.API_HOST + `/statis/selectZombieVehicleBox`, {
          parentId: id,
        })
          .then(data => {
            const info = data.data
            if (info.code == 200) {
              this.allCompanies.forEach(item=>{
                info.result.enterpriseList.forEach(item1=>{
                  if(item.enterpriseNo==item1.enterpriseNo){
                    item.count=item1.zombieVehicleTotal
                  }
                })
              })
            }
          })
      },
      //改变行政区 获取街道
      changeDistrict(parentId){
        this.parentId=parentId
        this.getTotalInfo(parentId)
        this.searchInfo.regionId = ""
        if(!this.searchInfo.enterpriseNo&&!this.parentId){
          //      打点
          this.showloading = true
          this.dataIndex = 0
           setTimeout(() => {
           this.getBigMapv(this.dataIndex)
           }, 1000)
        }else {
          this.changeDistribution()
        }

        if (!parentId) {
          this.streetData = []
          this.showAreaCenter()
          this.$store.state.districtData.forEach(item => {
            this.showArea(JSON.parse(item.regionPoints))
          })

          return
        }
        this.$store.state.districtData.forEach(item => {
          if(item.id==parentId){
            this.showAreaCenter(JSON.parse(item.regionPoints))
          }
        })
        this.axios.post(process.env.API_HOST + '/common/selectRegion', {parentId: parentId})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              this.streetData = result.result
              result.result.forEach(item => {
                this.showArea(JSON.parse(item.regionPoints))
              })
            }
          })
      },
      screenfullMap(){
        if (this.screenfull.enabled) {
          this.screenfull.toggle(this.$refs.mapScreenfull);
        }
      },

      getHotMap(){

        this.map = new BMap.Map("container", {
          enableMapClick: false,
          minZoom: 11,
          maxZoom: 19,

        });    // 创建Map实例

        this.map.centerAndZoom(new BMap.Point(114.188283, 22.667865), 11);  // 初始化地图,设置中心点坐标和地图级别
        this.map.addControl(new BMap.OverviewMapControl());
        this.map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
//        this.map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT}));
        this.map.enableScrollWheelZoom(); // 允许滚轮缩放
        this.map.setMapStyle({
          style: 'midnight'
        });
        this.changeDistrict(this.searchInfo.parentId)
//        地图点击事件
        setTimeout(()=>{
          this.addClickForMap()  //地图监听
        })
      },
      addClickForMap(){
        let _this = this
        this.map.addEventListener("click", function (e) {
          let point = e.point, regionName = "", searchInfo = {}, streetId = "",parentId
          _this.axios.post(process.env.API_HOST + `/common/selectRegionByPoint`, {lat: point.lat, lng: point.lng})
            .then(response => {
              const result = response.data
              if (result.code == 200) {
                if(_this.parentId&&_this.parentId!=result.result.id){
                  return
                }
                //调整视野绘制区域
                if (_this.parentId && result.result.child) { //有行政区 查询街道
                  regionName = result.result.regionName + result.result.child.regionName
                  parentId=result.result.id
                  streetId = result.result.child.id
                } else {  //无行政区 查询区域
                  regionName = result.result.regionName
                  parentId=0
                  streetId = result.result.id
                }

                _this.axios.post(process.env.API_HOST + `/statis/selectZombieVehicleBox`, {
                  parentId: parentId,
                  regionId: streetId,
                })
                  .then(data => {
                    const info = data.data
                    if (info.code == 200) {
                      if (info.result) {
                        _this.clickMapSearch(point, {...info.result,regionName:regionName})
                      }
                    }
                  })
              }
            })

        }, false)

      },
      clickMapSearch(point, info){
        let totalCount=0,contentIner="",regionId=0
        if(info.enterpriseList.length>0){
          totalCount=info.totalSum
          info.enterpriseList.forEach((item,key)=>{
            regionId=item.regionId
            let enterpriseName=item.enterpriseName?item.enterpriseName:"企业"+key
            contentIner+='<div style="padding: 0 10px;color: #50545D;">'+enterpriseName+'：' + item.zombieVehicleTotal + '</div> '
          })
        }
        let content, name = info.regionName, _this = this
        //创建检索信息窗口对象
        _this.mapInfoWindow = null;
        let exportBtn = '<div style="padding: 0 10px;"><button class="el-button el-button--primary el-button--small" onclick="exportZombieVehicle(this, '+ regionId +')">导出</button></div>'
        if(this.IEVersion()==-1){
          content = '<div class="mapTopWrap" > '+
            '<div class="mapTopWrap" > <div class="mapBaseTitle" style="border-right: 1px solid #EFEEF3;margin-right: -1px;">车辆统计</div> ' +
            '<div style="float: left;line-height: 30px;border-left: 1px solid #EFEEF3; "> <div style="padding: 0 10px;color: #50545D;">'+'总数'+'：' + totalCount + '</div> ' +contentIner+''+(this.$store.state.btnMenuIds.indexOf(312)>-1 ? exportBtn : '')+'</div></div> '              
        }else {
          content = '<div class="mapTopWrap" > '+
            '<div class="mapTopWrap" > <div style="color: #3975FE;font-size: 12px;padding-left: 10px;padding-bottom: 5px;">车辆统计</div> ' +
            '<div style="line-height: 25px;"><div style="padding: 0 10px;color: #50545D;">'+'总数'+'：' + totalCount + '</div>  ' +contentIner+''+(this.$store.state.btnMenuIds.indexOf(312)>-1 ? exportBtn : '')+'</div></div> '
        }

        _this.mapInfoWindow = new BMapLib.SearchInfoWindow(_this.map, content, {
          title: name,      //标题
          panel: "panel",         //检索结果面板
          enableAutoPan: true,     //自动平移
          offset: new BMap.Size(-20, -20),
          searchTypes: []
        });
        _this.mapClickMarker = new BMap.Marker(point); //创建marker对象
        _this.mapInfoWindow.open(_this.mapClickMarker)

      },
      getBigMapv(dataIndex){
        this.axios.get(this.fileStrList[dataIndex], {}).then(response => {
          this.mapData = response.data
          this.mapvSet(dataIndex)
        })
      },
      mapvSet(){
        if (this.mapData.length == 0) {
          return
        }
        var dataSet = new mapv.DataSet(this.mapData);
        var options = {
          splitList: this.$store.state.splitMapColors,
          size: 0.6,
          draw: 'category'
        }

        let mapvData = new mapv.baiduMapLayer(this.map, dataSet, options);
        this.dataIndex++
//        方式2
        if (this.dataIndex < this.fileStrList.length) {
          this.getBigMapv(this.dataIndex)
        }
        if (this.dataIndex == this.fileStrList.length - 1) {
          setTimeout(() => {
            this.showloading = false
          }, 1000)
        }
      },
      //百度提取区域经纬度
      showArea(areaPoints) {

        let _this = this, arr = []
        if (areaPoints && areaPoints.length > 2) {
        //  _this.map.clearOverlays();        //清除地图覆盖物
          areaPoints.forEach((item) => {
            arr.push(new BMap.Point(item.lng, item.lat))
          })
          //       Polyline  Polygon
          _this.ply = new BMap.Polygon(arr, {
            strokeColor: "#3975FE",    //边线颜色。
            fillColor: "white",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 1,       //边线的宽度，以像素为单位。
            strokeOpacity: 1,    //边线透明度，取值范围0 - 1。
            fillOpacity: 0.01,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
          });  //创建多边形

          _this.map.addOverlay(_this.ply);  //添加覆盖物
//          _this.ply.disableMassClear()
        }

      },
      //百度提取区域经纬度
      showAreaCenter(areaPoints) {
        let _this = this, arr = []
        _this.map.clearOverlays();
        if (areaPoints && areaPoints.length > 2) {
               //清除地图覆盖物
          areaPoints.forEach((item) => {
            arr.push(new BMap.Point(item.lng, item.lat))
          })
          //              Polyline  Polygon
          _this.ply = new BMap.Polyline(arr, {
            strokeColor: "#3975FE",    //边线颜色。
            fillColor: "white",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 1,       //边线的宽度，以像素为单位。
            strokeOpacity: 1,    //边线透明度，取值范围0 - 1。
            fillOpacity: 1,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
          });  //创建多边形

          _this.map.addOverlay(_this.ply);  //添加覆盖物
          _this.map.setViewport(_this.ply.getPath());    //调整视野
          _this.map.setZoom(13)

        } else {
          this.map.setCenter(new BMap.Point(114.14101345267, 22.6485544122), 11)
          _this.map.setZoom(11)
        }

      },
    },
    watch: {}
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../../common/stylus/mixin.styl"
  .zombieVehiclesWrap
    page()
    border-radius 5px
    .containerWrap
      height: 100%;
      width: 100%;
      padding 10px
      box-sizing border-box
      background-color white
      border-radius 5px
      position: relative;
      .loadingWrap
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        z-index 100
        background-color: rgba(0, 0, 0, 0.6);
        .loadingInner
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          top: 0;
          margin: auto;
          width: 100px;
          height: 100px;
          text-align: center;
          .loadingText
            color: #409eff;
            font-size: 12px;
      .infoButton
        width 20px
        height 20px
        font-size: 16px;
        color: #3975FE;
        position: absolute;
        top: 20px;
        right: 20px;
        z-index 5
        opacity: 0;
        .iconfont
          color #3975FE
          display: inline-block;
          font-size: 20px;
          cursor pointer
      .colorWrap
        position: absolute;
        left 10px;
        top: 10px;
        background-color rgba(255, 255, 255, 0.7)
        line-height 20px
        padding 10px
        border-radius 5px
        z-index: 5;
        color: black;
        margin-left: 60px;
        margin-top 10px;
        .colorlist
          display: inline-block;
          width: 10px;
          height 10px;
          border-radius: 50%;
          background-color: red;
          margin-right: 3px;
      #container
        height: 100%;
        width: 100%;
    .BMap_scaleCtrl
      bottom 20px !important
    .mapTopWrap
      background-color: white;
      overflow: hidden;
      min-height 90px;
      width 190px

      .mapBaseTitle
        color: #3975FE;
        font-size: 12px;
        writing-mode: vertical-lr;
        letter-spacing: 5px;
        float: left;
        padding: 11px;

    .BMapLib_SearchInfoWindow
      width 200px !important
      &::after
        content: ""
        position: absolute;
        background-color: white;
        width: 100px;
        height: 3px;
        bottom: 0px;
        left: 50px;
        z-index 100

    .BMapLib_bubble_title {
      padding-left: 14px !important;
      font-size: 14px !important;
      font-weight: bold !important;
      background-color white
      border-radius 10px !important
      /*display none !important*/
    }

    .BMapLib_bubble_top, .BMapLib_bubble_close {
      border-radius 10px !important
      border none !important
      background-color #f9f9f9 !important
    }

    #BMapLib_SearchInfoWindow0, .BMapLib_SearchInfoWindow {
      border-radius 10px !important
      /*min-width 200px !important*/
      box-shadow: 0px 0px 24px 0px rgba(0, 0, 0, 0.34) !important
      border none
    }

    .BMapLib_SearchInfoWindow .BMapLib_bubble_center {
      position static !important /*position absolute
      left 0
      top 31px*/
    }

    .BMapLib_bubble_content {
      min-height 100px !important
    }
</style>
